<?php
/**
 * Created by PhpStorm.
 * User: yiyu
 * Email: smalleasyu@gmail.com
 * Date: 2020-02-02 23:20:57
 * Desc:
 */

namespace app\api\controller;

use app\base\model\address\UserAddressInfo;
use app\core\exception\BusinessException;
use app\core\exception\ErrorCode;
use app\core\cache\RedisKeys;
use app\core\util\PreVentRepeatSubmitUtil;
use app\core\log\Log4dd;
use think\Request;

class AddressController extends ApiBaseController
{
    protected $beforeActionList = [
        'checkLogin',
        'checkAccountState',
    ];

    public function getDefaultAddress()
    {
        $data = UserAddressInfo::field(['user_id,is_del,wx_original_data,update_time'], true)->where('user_id',
            $this->user_id)->where('is_default', 1)->where('is_del', 0)->order('update_time',
            'desc')->find();

        return $this->successReturn(['has_default_address' => $data ? 1 : 0, 'address_info' => $data]);
    }

    public function setDefaultAddress()
    {
        $address_id = input('address_id/d', 0);

        if (empty($address_id)) {
            throw new BusinessException(ErrorCode::COMMON_LACK_PARAMS, '地址id不能为空');
        }

        $address_info = UserAddressInfo::field('user_id,is_default')->where('address_id', $address_id)->where('user_id',
            $this->user_id)->where('is_del', 0)->find();

        if (empty($address_info)) {
            throw new BusinessException(ErrorCode::DATA_NOT_FOUND, '地址不存在');
        }

        if ($address_info['is_default'] == 1) {
            throw new BusinessException(ErrorCode::COMMON_ERROR, '已经是默认地址，不用修改');
        }

        $res = UserAddressInfo::setDefaultAddress($address_id, $this->user_id);


        return $res ? $this->successReturn() : $this->errorReturn();

    }

    public function getAddressList()
    {
        $data = UserAddressInfo::field(['is_del,wx_original_data,update_time'], true)->where('user_id',
            $this->user_id)->where('is_del', 0)->order('is_default',
            'desc')->order('update_time', 'desc')->select();

        return $this->successReturn($data);
    }

    public function addAddress()
    {

        Log4dd::info('新增收货地址', [$this->user_id, Request::instance()->param(false)]);

        //防重复提交
        PreVentRepeatSubmitUtil::check(RedisKeys::getOperationAddressKey($this->user_id));

        if (UserAddressInfo::getEffectiveAddressNum($this->user_id) > UserAddressInfo::MAX_ADDRESS_NUM) {
            throw new BusinessException(ErrorCode::COMMON_ERROR, '当前地址已超有效个数上限');
        }

        $user_name = input('user_name/s', '', 'trim');
        $province_name = input('province_name/s', '', 'trim');
        $city_name = input('city_name/s', '', 'trim');
        $county_name = input('county_name/s', '', 'trim');
        $detail_info = input('detail_info/s', '', 'trim');
        $tel_number = input('tel_number/s', '', 'trim');
        $postal_code = input('postal_code/s', '', 'trim');
        $is_wx = input('is_wx/d', 0);
        $original_data = input('original_data/a', []);
        $is_default = input('is_default/d', 0);

        if (empty($user_name)) {
            throw new BusinessException(ErrorCode::COMMON_LACK_PARAMS, '收货人姓名不能为空');
        }

        //mb_strlen使用utf8 一个中文一个字节，一个英文一个字节

        if (mb_strlen($user_name, 'utf8') > 20) {
            throw new BusinessException(ErrorCode::COMMON_LACK_PARAMS, '收货人姓名不能超过20个中文字符，请检查');
        }

        if (empty($province_name)) {
            throw new BusinessException(ErrorCode::COMMON_LACK_PARAMS, '所在省不能为空');
        }

        if (mb_strlen($province_name, 'utf8') > 20) {
            throw new BusinessException(ErrorCode::COMMON_LACK_PARAMS, '所在省不能超过20个中文字符，请检查');
        }

        if (empty($city_name)) {
            throw new BusinessException(ErrorCode::COMMON_LACK_PARAMS, '所在市不能为空');
        }

        if (mb_strlen($city_name, 'utf8') > 27) {
            throw new BusinessException(ErrorCode::COMMON_LACK_PARAMS, '所在市不能超过27个中文字符，请检查');
        }

        //有些地区没有第三级，暂不判断，例如佛山

        if (empty($detail_info)) {
            throw new BusinessException(ErrorCode::COMMON_LACK_PARAMS, '详细收货地址不能为空');
        }

        if (mb_strlen($detail_info) > 80) {
            throw new BusinessException(ErrorCode::COMMON_LACK_PARAMS, '详细收货地址不能超过80个中文字符，请检查');
        }

        if (empty($tel_number)) {
            throw new BusinessException(ErrorCode::COMMON_LACK_PARAMS, '收货人手机号不能为空');
        }

        $exist = UserAddressInfo::where('user_id', $this->user_id)
            ->where('receive_name', $user_name)
            ->where('receive_phone', $tel_number)
            ->where('province_name', $province_name)
            ->where('city_name', $city_name)
            ->where('area_name', $county_name)
            ->where('address_detail', $detail_info)
            ->find();

        if ($exist) {
            if ($exist['is_del'] == 1) {
                UserAddressInfo::where('address_id', $exist['address_id'])->update(['is_del' => 0]);
            }
            $this->successReturn($exist, '创建成功');
        }

        $data = [
            'user_id' => $this->user_id,
            'receive_name' => $user_name,
            'receive_phone' => $tel_number,
            'postal_code' => $postal_code,
            'province_name' => $province_name,
            'city_name' => $city_name,
            'area_name' => $county_name,
            'address_detail' => $detail_info,
            'is_del' => 0,
            'is_default' => $is_default,
            'create_time' => date('Y-m-d H:i:s')
        ];

        if ($original_data) {
            $data['wx_original_data'] = $original_data;
        }

        if ($is_default == 1) {
            UserAddressInfo::where('user_id', $this->user_id)->update(['is_default' => 0]);
        }

        $is_default_num = UserAddressInfo::where('user_id', $this->user_id)
            ->where('is_default', 1)
            ->where('is_del', 0)
            ->count();

        if ($is_default_num == 0) {
            $data['is_default'] = 1;
        }

        $res = UserAddressInfo::create($data);

        return $res ? $this->successReturn($data, '创建成功') : $this->errorReturn();
    }

    public function updateAddress()
    {
        Log4dd::info('修改收货地址', [$this->user_id, Request::instance()->param(false)]);

        //防重复提交
        PreVentRepeatSubmitUtil::check(RedisKeys::getOperationAddressKey($this->user_id));

        $address_id = input('address_id/d', 0);

        if (empty($address_id)) {
            throw new BusinessException(ErrorCode::COMMON_LACK_PARAMS, '地址id不能为空');
        }

        $address_info = UserAddressInfo::field('user_id,is_default')->where('address_id', $address_id)->where('user_id',
            $this->user_id)->where('is_del', 0)->find();

        if (empty($address_info)) {
            throw new BusinessException(ErrorCode::DATA_NOT_FOUND, '地址不存在');
        }

        $user_name = input('user_name/s', '', 'trim');
        $province_name = input('province_name/s', '', 'trim');
        $city_name = input('city_name/s', '', 'trim');
        $county_name = input('county_name/s', '', 'trim');
        $detail_info = input('detail_info/s', '', 'trim');
        $tel_number = input('tel_number/s', '', 'trim');
        $postal_code = input('postal_code/s', '', 'trim');
        $is_wx = input('is_wx/d', 0);
        $original_data = input('original_data/a', []);
        $is_default = input('is_default/d', 0);

        if (empty($user_name)) {
            throw new BusinessException(ErrorCode::COMMON_LACK_PARAMS, '收货人姓名不能为空');
        }

        //mb_strlen使用utf8 一个中文一个字节，一个英文一个字节

        if (mb_strlen($user_name, 'utf8') > 20) {
            throw new BusinessException(ErrorCode::COMMON_LACK_PARAMS, '收货人姓名不能超过20个中文字符，请检查');
        }

        if (empty($province_name)) {
            throw new BusinessException(ErrorCode::COMMON_LACK_PARAMS, '所在省不能为空');
        }

        if (mb_strlen($province_name, 'utf8') > 20) {
            throw new BusinessException(ErrorCode::COMMON_LACK_PARAMS, '所在省不能超过20个中文字符，请检查');
        }

        if (empty($city_name)) {
            throw new BusinessException(ErrorCode::COMMON_LACK_PARAMS, '所在市不能为空');
        }

        if (mb_strlen($city_name, 'utf8') > 27) {
            throw new BusinessException(ErrorCode::COMMON_LACK_PARAMS, '所在市不能超过27个中文字符，请检查');
        }

        //有些地区没有第三级，暂不判断，例如佛山

        if (empty($detail_info)) {
            throw new BusinessException(ErrorCode::COMMON_LACK_PARAMS, '详细收货地址不能为空');
        }

        if (mb_strlen($detail_info) > 80) {
            throw new BusinessException(ErrorCode::COMMON_LACK_PARAMS, '详细收货地址不能超过80个中文字符，请检查');
        }

        if (empty($tel_number)) {
            throw new BusinessException(ErrorCode::COMMON_LACK_PARAMS, '收货人手机号不能为空');
        }

        $data = [
            'user_id' => $this->user_id,
            'receive_name' => $user_name,
            'receive_phone' => $tel_number,
            'postal_code' => $postal_code,
            'province_name' => $province_name,
            'city_name' => $city_name,
            'area_name' => $county_name,
            'address_detail' => $detail_info,
            'is_del' => 0,
            'is_default' => $is_default,
            'create_time' => date('Y-m-d H:i:s')
        ];

        if ($original_data) {
            $data['wx_original_data'] = $original_data;
        }

        $is_default_num = UserAddressInfo::where('user_id', $this->user_id)
            ->where('is_default', 1)
            ->where('is_del', 0)
            ->count();

        if ($is_default_num == 0) {
            $data['is_default'] = 1;
        }

        $res = UserAddressInfo::where('address_id', $address_id)->update($data);

        return $res ? $this->successReturn($data, '修改成功') : $this->errorReturn();
    }

    public function delAddress()
    {
        $address_id = input('address_id/d', 0);

        if (empty($address_id)) {
            throw new BusinessException(ErrorCode::COMMON_LACK_PARAMS, '地址id不能为空');
        }

        $address_info = UserAddressInfo::field('user_id,is_default')->where('address_id', $address_id)->where('user_id',
            $this->user_id)->where('is_del', 0)->find();

        if (empty($address_info)) {
            throw new BusinessException(ErrorCode::DATA_NOT_FOUND, '地址不存在');
        }

        /*//删除地址时如果地址为默认
        if ($address_info['is_default'] == 1) {
            throw new BusinessException(ErrorCode::COMMON_ERROR, '不能删除默认地址');
        }*/

        $res = UserAddressInfo::where('address_id', $address_id)->update(['is_del' => 1, 'is_default' => 0]);

        return $res ? $this->successReturn() : $this->errorReturn();
    }

}